#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Copyright © 启明星辰 版权所有
# @Time    : 2023/6/20 14:19
# @Author  : 胡浩浩
# @Email   : hu_haohao@venusgroup.com.cn
# @File    : user_login.py
# @IDE     : PyCharm
# @description :
import hashlib
import math
import random
import time

import requests
import urllib3
urllib3.disable_warnings()



class UserLogin:
    def __init__(self, host, username, password):
        self.host = host
        self.session = requests.session()
        self.username = username
        self.password = password

    def sha256(self, string):
        """
                针对给定的string字符串进行sha256加密
            :param string:
            :return: 返回sha256加密后的数据
            """
        sha256 = hashlib.sha256()
        sha256.update(string.encode("utf-8"))
        return sha256.hexdigest()

    def sha1(self, string):
        """
            针对给定的string字符串进行sha1加密
        :param string:
        :return: 返回sha1加密胡的数据
        """
        sha1 = hashlib.sha1()
        sha1.update(string.encode("utf-8"))
        return sha1.hexdigest()

    def get_env(self):
        timestamp = str(int(1000 * time.time()))
        # print(timestamp)
        nonce = str(random.randint(1000000, 999999999))
        signature = self.sha256(timestamp + "$" + nonce)
        data = {
            "timestamp": timestamp,
            "nonce": nonce,
            "signature": signature
        }
        response = self.session.post(self.host + '/api/v2/env', data=data, verify=False)

        # print(response.text)
        ticket = str(response.json()["data"]["ticket"])
        modulus = str(response.json()["data"]["modulus"])
        exponent = str(response.json()["data"]["exponent"])
        voucher = str(response.json()["data"]["voucher"])
        return ticket, modulus, exponent, voucher

    def get_captcha(self, voucher, ticket):
        data = {
            "voucher": voucher,
            "ticket": ticket
        }
        response = self.session.post(self.host + '/api/v2/captcha', data=data, verify=False)

        # print(response.text)
        captcha = response.json()["data"]["captcha"]
        return captcha

    def get_password(self, pwd: str, exponent: str, modulus: str) -> str:
        """
        盘古2.0登录密码加密
        简单来说：来自网络

        :param pwd: 密码原文
        :param exponent: 幂数 (hex_str)
        :param modulus: 模数 (hex_str)
        :return: 加密后的密码
        """
        pwd_sha1 = hashlib.sha1(pwd.encode('utf-8')).hexdigest()

        exponent_int = int.from_bytes(bytes.fromhex(exponent), byteorder='big')
        modulus_int = int.from_bytes(bytes.fromhex(modulus), byteorder='big')
        pwd_sha1_int = int.from_bytes(pwd_sha1[::-1].encode('utf-8'), byteorder='big')  # 这里需要把待加密明文反向一下，但是我也不知道为啥

        encrypted_nr = pow(pwd_sha1_int, exponent_int, modulus_int)  # nr不知道是啥意思，抄的别人的就是nr
        key_length = math.ceil(modulus_int.bit_length() / 8)

        encrypted_pwd = encrypted_nr.to_bytes(key_length, byteorder='big')
        return encrypted_pwd.hex()

    def user_login(self):
        ticket, modulus, exponent, voucher = self.get_env()
        captcha = self.get_captcha(voucher, ticket)
        # print(captcha)
        password = self.get_password(self.password, exponent, modulus)
        # print(password)
        data = {
            "username": self.username,
            "password": password,
            "voucher": voucher,
            "captcha": captcha,
            "ticket": ticket,
            "code": ""
        }
        response = self.session.post(self.host + '/api/v2/signin', data=data, verify=False)
        # print(response.text)
        self.session.headers["Authorization"] = f"Bearer {response.json()['data']['token']}"
        self.session.headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
        # print(self.session.headers)
        return self.session, response.json()['data']['token']
